/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
Ext.chart.Chart.CHART_URL = '../../../ext3/resources/charts.swf';
Ext.QuickTips.init();
var _pageSize = 20;
var _title = currentOrgName + ' 监测点月数据补采';
var store;
var now = new Date();
var saveServlet = '../../../servlet/data/YsjSave';
var loadServlet = '../../../servlet/data/YsjLoad';
var fieldName = ['name', 'shortName', 'pointType', 'pointType2', 'dataTime', 'voltageLevelName',
    'maxVoltage', 'maxVoltageTime', 'minVoltage', 'minVoltageTime', 'avgVoltage',
    'defaultTotalTime', 'aboveUpperLimitMin', 'aboveUpperLimitNumber', 'underLowerLimitMin', 'underLowerLimitNumber', 'totalRunMin', 'rate', 'dataYear', 'dataMonth', 'dataDay',
    'id', 'isOffline', 'deviceId', 'pointId', 'type', 'status', 'reasonAnalyze', 'treatWay', 'completeCase', 'note', 'did','yStatus','ynote'];
var fieldLabel = ['测点名称', '单位名称', '测点类别', '电网类别', '日期', '电压等级<br/>(kv)', '最高电压', '最高电压时间', '最低电压', '最低电压时间', '平均电压', '故障时间<br/>（分钟）',
    "超上限时间<br/>（分钟）", "超上限<br/>次数", "超下限时间<br/>（分钟）", "超下限<br/>次数", '总时间<br/>（分钟）', '合格率（%）', '年', '月', '日', 'ID', '在线离线', '设备ID', '监测点ID',
    '类型', '状态', '原因分析', '处理', '完成情况', '备注'];


var uploadForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'UploadForm',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: '../../../servlet/task/TaskUploadSave',
            items: [{
                    name: 'pointNames',
                    xtype: 'textarea',
                    id: 'PointNamesUpload',
                    width: 180,
                    height: 200,
                    readOnly: true,
                    disable: true,
                    fieldLabel: '所选监测点',
                    allowBlank: false,
                    blankText: '监测点名称必须填写'
                }
            ],
            buttons: [{
                    text: '确定',
                    iconCls: 'icon-save',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                winUpload.hide();
                                Ext.Msg.alert("系统提示", action.result.msg);
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('系统提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('系统提示', action.result.msg);
                                }
                            },
                            params: {cmd: 'createYTask'}
                        };
                        //alert(checkboxSel.getSelections().length);
                        var ids = getIds(checkboxSel.getSelections());
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        //submitConfig.params.deviceIds = ids.deviceIds;
                        submitConfig.params.pointIds = ids.pointIds;
                        submitConfig.params.dates = beginDate;
                        Ext.getCmp('UploadForm').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        winUpload.hide();
                    }
                }]
        }
);
var winUpload = new Ext.Window({
    title: _title,
    layout: 'form',
    width: 400,
    autoHeight: true,
    closeAction: 'hide',
    items: [uploadForm]
});



function taskUpload() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择，请选择需要上传的监测点");
    } else {
       var rs  = checkboxSel.getSelections();
        for(var i =0;i<rs.length;i++){
            //var did = rs[i].get("did");
            var pointId =rs[i].get("pointId");
            var status = rs[i].get("status");
            if(!pointId){
                Ext.Msg.alert("系统提示","数据缺失");
                return;
            }
//            if(status){
//                status = parseInt(status);
//                status = Math.floor(status%100000/10000);
//                if(status ===0){
//                    Ext.Msg.alert("系统提示","存在不上报测点");
//                    return;
//                }
//            }
        }
        var pointNames = getFields(checkboxSel.getSelections(), 'name');
        Ext.getCmp('PointNamesUpload').setValue(pointNames);
        //Ext.getCmp('ReportStatusCombo').setValue();
        winUpload.show();
    }
}

function taskUploadAll() {
    if (currentOrgCode.length != 4) {
        Ext.Msg.alert("系统提示", "只允许市级公司进行操作");
        return;
    }
    var myMask = new Ext.LoadMask(Ext.getBody(), {msg: "请稍候..."});
    myMask.show();
    var date = Ext.getCmp("dateFrom").getValue().format('Ym');
    var token1 = new Date().getTime();
    var params = {token:token,token1:token1,cmd: "createYTaskAll", date: date};
    
    Ext.Ajax.request({
        url: '../../../servlet/task/TaskUploadSave',
        //timeout: 50000,
        success: function(response, options) {
            //alert(response.responseText);
            var obj = Ext.decode(response.responseText);
            if (obj.success) {
                Ext.Msg.alert("系统提示", "上报任务添加成功");
            } else {
                Ext.Msg.alert("系统提示", obj.msg);
            }
            myMask.hide();
        },
        failure: function(response, opts) {
            Ext.Msg.alert('系统提示', '生成失败，清稍候再试 ' + response.status);
            myMask.hide();
        },
        params: params
    });

}

var beginDate = now.format('Ym');
var checkboxSel = new Ext.grid.CheckboxSelectionModel();
var store;
function buildWindow() {
    store = new Ext.data.JsonStore({
        url: loadServlet,
        root: 'data',
        idProperty: 'id',
        totalProperty: 'count',
        fields: fieldName,
        autoLoad: true,
        baseParams: {cmd: 'recallLock', start: 0, limit: _pageSize, beginDate: now.format('Ym'), endDate: now.format('Ym')}
    });
    tbarPoint = new Ext.Toolbar({
        items: [
            pointTypeCombo, pointType2Combo, voltageLevelCombo, reportCombo, haveCombo
                    , pointText, searchButton
        ]
    });
    tbarPoint.insert(0, {
        xtype: 'datefield',
        id: 'dateFrom',
        format: 'Y年m月',
        width: 150,
        value: now,
        listeners: {
            select: function(c, date) {
                beginDate = date.format('Ym');
                store.baseParams.beginDate = beginDate;
                store.baseParams.endDate = beginDate;
            }
        }
    }
    );

    var grid = new Ext.grid.GridPanel({
        //title: _title,
        store: store,
        sm: checkboxSel,
        columns: [
            checkboxSel,
            new Ext.grid.RowNumberer({width: 40, header: '序号'}),
            {header: 'PointId', dataIndex: 'pointId', hidden: true},
            {header: '上传', dataIndex: 'yStatus',width:40,
                renderer: function(v, metaData, record, rowIndex, colIndex, store) {
                    var value = Math.floor((parseInt(v) % 1000) / 100);
                    var imageName;
                    if (value > 0) {
                        imageName = 'record_green.png';
                        return "<image src='" + basePath + "image/icon/" + imageName + "'/>";
                    } else
                        imageName = 'record_red.png';
                    return "<image src='" + basePath + "image/icon/" + imageName + "'/>";
                }
            },
            {header: fieldLabel[0], sortable: true, dataIndex: fieldName[0]},
            {header: fieldLabel[1], width: 80, sortable: true, dataIndex: fieldName[1]},
            {header: fieldLabel[2], width: 60, sortable: true, dataIndex: fieldName[2]},
            {header: '在线', width: 60, sortable: true, dataIndex: 'isOffline'},
            {header: fieldLabel[3], width: 60, sortable: true, dataIndex: fieldName[3]},
            {header: fieldLabel[5], width: 80, sortable: true, dataIndex: fieldName[5]},
            {header: fieldLabel[17], width: 100, sortable: true, align: 'right',format:'0.000',
                renderer: function(value, metaData, record, rowIndex, colIndex, store) {
                    var upper = record.get('aboveUpperLimitMin');
                    var lower = record.get('underLowerLimitMin');
                    var total = record.get('totalRunMin');
                    var rate = (1 - (parseInt(upper) + parseInt(lower)) / parseInt(total))*100;
                    
                    //alert(rate);
                    return rate.toFixed(3);
                }
            },
            {header: fieldLabel[6], width: 80, sortable: true, dataIndex: fieldName[6]},
            {header: fieldLabel[7], width: 100, sortable: true, dataIndex: fieldName[7], xtype: 'datecolumn', format: 'Y-m-d H:i:s'},
            {header: fieldLabel[8], width: 80, sortable: true, dataIndex: fieldName[8]},
            {header: fieldLabel[9], width: 100, sortable: true, dataIndex: fieldName[9], xtype: 'datecolumn', format: 'Y-m-d H:i:s'},
            {header: fieldLabel[10], width: 80, sortable: true, dataIndex: fieldName[10]},
            {header: fieldLabel[11], width: 80, sortable: true, dataIndex: fieldName[11]},
            {header: fieldLabel[12], width: 80, sortable: true, dataIndex: fieldName[12]},
            //{header: fieldLabel[13], width: 50, sortable: true, dataIndex: fieldName[13]},
            {header: fieldLabel[14], width: 80, sortable: true, dataIndex: fieldName[14]},
            //{header: fieldLabel[15], width: 50, sortable: true, dataIndex: fieldName[15]},
            {header: fieldLabel[16], width: 80, sortable: true, dataIndex: fieldName[16]},
            {header: '备注', width: 120, sortable: true, dataIndex: 'ynote'}
        ],
        loadMask: true,
        tbar: new Ext.Toolbar([            
            {
                text: '任务上报',
                iconCls: 'icon-linkratio',
                handler: taskUpload
            },{
                text:'全部上报',
                iconCls:'icon-linkratio',
                handler:taskUploadAll
            }
        ]),
        listeners: {
            'render': function() {
                tbarPoint.render(this.tbar);
            }
        },
        bbar: new Ext.PagingToolbar({
            pageSize: _pageSize,
            store: store,
            displayInfo: true,
            displayMsg: '显示记录：{0} - {1}   总记录：{2}',
            emptyMsg: '目前没有信息'
        })
    });

    var applicationUI = new Ext.Viewport({
        layout: "fit",
        items: [
            grid
        ]
    });
}
Ext.onReady(buildWindow);
